#include "data_define.h"

#include "esp_log.h"
#include "esp_system.h"
#include "nvs.h"
#include "nvs_flash.h"
#include "string.h"
const static char *TAG = "nvs";
char g_mac_str[18];
g_cfg_t g_cfg = {
    .wifi_ssid = "zzh",
    .wifi_pass = "zhangxuanyu",
    .tcp_server_ip = "192.168.0.111",
    .tcp_server_port = 1234,
    .temp_k = 1.0f,
    .temp_b = 0.0f,
    .humi_k = 1.0f,
    .humi_b = 0.0f,
    .collect_interval = 10,
    .upload_interval = 10,
};
g_cfg_t default_cfg = {
    .wifi_ssid = "zzh",
    .wifi_pass = "zhangxuanyu",
    .tcp_server_ip = "192.168.0.111",
    .tcp_server_port = 1234,
    .temp_k = 1.0f,
    .temp_b = 0.0f,
    .humi_k = 1.0f,
    .humi_b = 0.0f,
    .collect_interval = 10,
    .upload_interval = 10,
};
esp_err_t nvs_init(void) {
  esp_err_t err = nvs_flash_init();
  if (err == ESP_ERR_NVS_NO_FREE_PAGES /*  */
      || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
    ESP_ERROR_CHECK(nvs_flash_erase());
    err = nvs_flash_init();
  }
  return err;
}

esp_err_t save_config_nvs(g_cfg_t *cfg) {
  nvs_handle_t my_handle;
  esp_err_t err;
  err = nvs_open("storage", NVS_READWRITE, &my_handle);
  if (err != ESP_OK) {
    ESP_LOGE("nvs", "Error (%s) opening NVS handle!\n", esp_err_to_name(err));
    return err;
  }
  err = nvs_set_blob(my_handle, "cfg", cfg, sizeof(g_cfg_t));
  if (err != ESP_OK) {
    ESP_LOGE("nvs", "Error (%s) writing!\n", esp_err_to_name(err));
    nvs_close(my_handle);
  }

  err = nvs_commit(my_handle);
  if (err != ESP_OK) {
    ESP_LOGE("nvs", "Error (%s) committing!\n", esp_err_to_name(err));
  }
  nvs_close(my_handle);
  return err;
}

esp_err_t load_config_nvs(g_cfg_t *cfg) {
  nvs_handle_t my_handle;
  esp_err_t err;

  err = nvs_open("storage", NVS_READWRITE, &my_handle);
  if (err != ESP_OK) {
    ESP_LOGE("nvs", "Error (%s) opening NVS handle!\n", esp_err_to_name(err));
    return err;
  }
  ESP_LOGI("nvs", "Reading config from NVS");
  size_t required_size = sizeof(g_cfg_t);
  err = nvs_get_blob(my_handle, "cfg", cfg, &required_size);
  if (err != ESP_OK && err != ESP_ERR_NVS_NOT_FOUND) {
    ESP_LOGE("nvs", "Error (%s) reading!\n", esp_err_to_name(err));
    nvs_close(my_handle);
    return err;
  }

  if (err != ESP_OK && err == ESP_ERR_NVS_NOT_FOUND) {
    ESP_LOGI(TAG, "new flash write default");

    err = nvs_set_blob(my_handle, "config", &default_cfg, sizeof(g_cfg_t));
    if (err != ESP_OK) {
      ESP_LOGE(TAG, "Failed to write config to NVS");
      nvs_close(my_handle);
      return err;
    }
    err = nvs_commit(my_handle);
    if (err != ESP_OK) {
      ESP_LOGE(TAG, "Failed to commit config to NVS");
    }
  }

  nvs_close(my_handle);
  return err;
}
